package com.yjyw.tiexie.view.popupwindow;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.yjyw.tiexie.BuildConfig;
import com.yjyw.tiexie.R;
import com.yjyw.tiexie.bean.MainChangeEvent;
import com.yjyw.tiexie.common.permission.IPermission;
import com.yjyw.tiexie.common.permission.PermissionManager;
import com.yjyw.tiexie.util.DownloadUtil;
import com.yjyw.tiexie.util.LogUtil;
import com.yjyw.tiexie.util.ViewUtils;
import com.yjyw.tiexie.util.update.AppUpdateDialog;
import com.yjyw.tiexie.util.update.NumberProgressBar;
import com.yjyw.tiexie.util.update.OnDownloadListener;
import com.yjyw.tiexie.util.update.VersionUpdateAdapter;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.List;

/**
 * Created on 2019/8/12.
 *
 * @author ${AUTHOR}
 * TODO:
 */
public class AppUpdateWindow {
    Dialog dialog;
    Window window;
    private RecyclerView rv;
    private Activity context;
    //下载的进度条
    private NumberProgressBar npb;
    private static final int INSTALL_PACKAGES_REQUESTCODE = 113;
    private static final int GET_UNKNOWN_APP_SOURCES = 114;

    //下载工具类
    private DownloadUtil downloadUtil;

    private String urlName;
    private Uri apkUri;
    //更新安装包地址
    private String url;

    public String getUrlName() {
        return urlName;
    }

    public void setUrlName(String urlName) {
        this.urlName = urlName;
    }

    public Uri getApkUri() {
        return apkUri;
    }

    public void setApkUri(Uri apkUri) {
        this.apkUri = apkUri;
    }

    public AppUpdateWindow(AppUpdateDialog dialog, Activity context) {

    }

    public AppUpdateWindow() {
    }

    private static AppUpdateWindow appUpdateWindow;

    public static AppUpdateWindow getAppUpdateUtil() {
        if (appUpdateWindow == null) {
            appUpdateWindow = new AppUpdateWindow();
        }
        return appUpdateWindow;
    }

    public Window getWindow() {
        return window;
    }

    public void intWindow(Dialog mDialog, List<String> updateContent, String newVersion, Boolean isForce, String url, Activity mcontext) {
        this.context = mcontext;
        this.dialog = mDialog;
        window = dialog.getWindow();
        this.url = url;

        window.getDecorView().setPadding(0, 0, 0, 0);
        window.setGravity(Gravity.CENTER);
        window.setContentView(R.layout.popupwindow_version_update);

        window.setWindowAnimations(R.style.AnimBottom);

        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);

        View view = window.getDecorView();
        TextView tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
        TextView tv_update = (TextView) view.findViewById(R.id.tv_update);
        TextView tv_version_code = (TextView) view.findViewById(R.id.tv_version_code);
        tv_version_code.setText(newVersion + "版本更新");

        if (isForce) {
            tv_cancel.setVisibility(View.GONE);
        } else {
            tv_cancel.setVisibility(View.VISIBLE);
        }


        rv = (RecyclerView) view.findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(context));
        VersionUpdateAdapter versionUpdateAdapter = new VersionUpdateAdapter(context, updateContent);
        if (updateContent.size() > 5) {
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) rv.getLayoutParams();
            layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT;
            layoutParams.height = ViewUtils.dip2px(context, 15) * 5 + ViewUtils.dip2px(context, 10);
        }
        rv.setAdapter(versionUpdateAdapter);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tv_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                window.setContentView(R.layout.popupwindow_download_progress_layout);
                View view = window.getDecorView();
                npb = (NumberProgressBar) view.findViewById(R.id.npb);
                TextView tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
                TextView tv_dismiss = (TextView) view.findViewById(R.id.tv_dismiss);

//                //检查读写权限并且下载
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
//                    //android11 适配
//                    XXPermissions.with(context)
//                            // 不适配 Android 11 可以这样写
//                            //.permission(Permission.Group.STORAGE)
//                            // 适配 Android 11 需要这样写，这里无需再写 Permission.Group.STORAGE
//                            .permission(Permission.MANAGE_EXTERNAL_STORAGE)
//                            .request(new OnPermissionCallback() {
//
//                                @Override
//                                public void onGranted(List<String> permissions, boolean all) {
//                                    if (all) {
//                                        try {
//                                            LogUtil.e("MANAGE_EXTERNAL_STORAGE", all + "");
//                                            download();
//                                        } catch (Exception e) {
//                                            e.printStackTrace();
//                                        }
//                                    }
//                                }
//
//                                @Override
//                                public void onDenied(List<String> permissions, boolean never) {
//                                    if (never) {
//                                        ToastUtil.show("被永久拒绝授权，请手动授予存储权限");
//                                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
//                                        XXPermissions.startPermissionActivity(mcontext, permissions);
//                                    } else {
//                                        ToastUtil.show("获取存储权限失败");
//                                    }
//                                }
//                            });
//                } else {
//                    check();
//                }
                check();

                tv_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        context.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                downloadUtil = DownloadUtil.get();
                                downloadUtil.cancleDown();
                                dialog.dismiss();
                            }
                        });
                    }
                });
                tv_dismiss.setOnClickListener(new View.OnClickListener() {//
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
            }
        });
        //如果是强制更新设置外部不可点击
        if (isForce) {
            dialog.setCanceledOnTouchOutside(false);
        } else {
            dialog.setCanceledOnTouchOutside(true);
        }
    }

    private static final int WRITE_EXTERNAL = 1005;

    @IPermission(WRITE_EXTERNAL)
    public void check() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (PermissionManager.hasPermissions(context, perms)) {//授权通过
            try {
                download();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {//请求授权
            PermissionManager.requestPermissions(context, WRITE_EXTERNAL, perms);
        }
    }


    private void download() throws Exception {
        downloadUtil = DownloadUtil.get();
        LogUtil.e("download", "url" + url);
        downloadUtil.download(url, "/" + BuildConfig.MX_USER_TYPE + "/apk", new OnDownloadListener() {
            @Override
            public void onDownloadSuccess(final String NameFromUrl) {
                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        LogUtil.e("download", "download" + NameFromUrl);
                        urlName = NameFromUrl;

//                        showMessage("下载成功，准备安装");
                        //获得下载安装包的路径
                        File downloads = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
                        File downloadFile = new File(downloads + "/" + BuildConfig.MX_USER_TYPE + "/apk/"+  NameFromUrl);

//                        Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/" + BuildConfig.MX_USER_TYPE + "/apk/" + NameFromUrl));
                        Uri uri = Uri.fromFile(downloadFile);
                        apkUri = uri;
                        LogUtil.e("downloaduri", uri + "");

                        //下载成功 apkUri urlName  在activity记录
                        EventBus.getDefault().post(new MainChangeEvent("3",NameFromUrl,uri));

                        //执行安装的方法
//                        AppUpdateUtil.getAppUpdateUtil().installAPK(uri, getApplicationContext(), NameFromUrl);
                        installAPK(uri, context, NameFromUrl);

                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }
                });
            }

            @Override
            public void onDownloading(final int progress) {
                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (npb != null) {
                            npb.setProgress(progress);
                        }
                    }
                });

            }

            @Override
            public void onDownloadFailed() {
                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        showMessage("下载失败");
                    }
                });
            }
        });
    }


    private void installAPK(Uri apk, Activity context, String apkname) {
        if (Build.VERSION.SDK_INT <= 23) {
            Intent intents = new Intent();
            intents.setAction("android.intent.action.VIEW");
            intents.addCategory("android.intent.category.DEFAULT");
            intents.setType("application/vnd.android.package-archive");
            intents.setData(apk);
            intents.setDataAndType(apk, "application/vnd.android.package-archive");
            intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intents);
        } else if (Build.VERSION.SDK_INT >= 26) {
            boolean b = context.getPackageManager().canRequestPackageInstalls();
            if (b) {
//                File file = new File(Environment.getExternalStorageDirectory() + "/" + BuildConfig.MX_USER_TYPE + "/apk/" + apkname);
                File downloads = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
                File file = new File(downloads  + "/" + BuildConfig.MX_USER_TYPE+ "/apk/" + apkname);
                if (file.exists()) {
                    openFile(file, context);
                }
            } else {
                //请求安装未知应用来源的权限
                checkUpdate(context, urlName);
            }
        } else {
//            File file = new File(Environment.getExternalStorageDirectory() + "/" + BuildConfig.MX_USER_TYPE + "/apk/" + apkname);
            File downloads = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
            File file = new File(downloads  + "/" + BuildConfig.MX_USER_TYPE+ "/apk/" + apkname);
            if (file.exists()) {
                openFile(file, context);
            }
        }
    }

    @IPermission(INSTALL_PACKAGES_REQUESTCODE)
    public void checkUpdate(Activity context, String urlName) {
        String[] perms = {Manifest.permission.REQUEST_INSTALL_PACKAGES};
        if (PermissionManager.hasPermissions(context, perms)) {//授权通过
            LogUtil.e("checkUpdate", "授权通过");
//            File file = new File(Environment.getExternalStorageDirectory() + "/" + BuildConfig.MX_USER_TYPE + "/apk/" + urlName);
            File downloads = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
            File file = new File(downloads  + "/" + BuildConfig.MX_USER_TYPE+ "/apk/" + urlName);
            if (file.exists()) {
                LogUtil.e("checkUpdate", "openFile");
                openFile(file, context);
            }

        } else {//请求授权
//            Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
//            context.startActivityForResult(intent, GET_UNKNOWN_APP_SOURCES);
            Intent intent = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                //此方法需要API>=26才能使用
                toInstallPermissionSettingIntent(context);
                LogUtil.e("onActivityResult", "请求授权");
            }
        }
    }

    /**
     * 开启安装未知来源权限
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void toInstallPermissionSettingIntent(Activity context) {
        LogUtil.e("toInstallPermissionSettingIntent", "start");
        Uri packageURI = Uri.parse("package:" + context.getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        context.startActivityForResult(intent, GET_UNKNOWN_APP_SOURCES);
        LogUtil.e("toInstallPermissionSettingIntent", packageURI + "");
    }

    /**
     * 待封装
     */
    private void openFile(File file, Context context) {
        Intent intent = new Intent(Intent.ACTION_VIEW);

        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        Uri bmpUri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);

        intent.setDataAndType(bmpUri, "application/vnd.android.package-archive");

        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        LogUtil.e("openFile", "bmpUri" + bmpUri);
        try {
            context.startActivity(intent);
        } catch (Exception var5) {
            var5.printStackTrace();
            Toast.makeText(context, "没有找到打开此类文件的程序", Toast.LENGTH_SHORT).show();
        }

    }


    /**
     * 待封装
     */
    public void checkIsAndroidO(Uri apkUri, Activity context, String urlName) {
        LogUtil.e("checkIsAndroidO", "urlName:" + urlName);
        if (Build.VERSION.SDK_INT <= 23) {
            Intent intents = new Intent();
            intents.setAction("android.intent.action.VIEW");
            intents.addCategory("android.intent.category.DEFAULT");
            intents.setType("application/vnd.android.package-archive");
            intents.setData(apkUri);
            intents.setDataAndType(apkUri, "application/vnd.android.package-archive");
            intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intents);
        } else if (Build.VERSION.SDK_INT >= 26) {
            LogUtil.e("checkIsAndroidO", "start");
            boolean b = context.getPackageManager().canRequestPackageInstalls();
            if (b) {
                LogUtil.e("checkIsAndroidO", "" + b);
                //图片沙盒文件夹
                File downloads = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
                File file = new File(downloads  + "/" + BuildConfig.MX_USER_TYPE+ "/apk/" + urlName);
//                File file = new File(Environment.getExternalStorageDirectory() + "/" + BuildConfig.MX_USER_TYPE + "/apk/" + urlName);
//                LogUtil.e("checkIsAndroidO", "" + file.exists());
                LogUtil.e("checkIsAndroidO", "urlName:" + urlName);
                try {
                    if (file.exists()) {
                        LogUtil.e("checkIsAndroidO", "openFile");
                        openFile(file, context);
                    }
                } catch (Exception e) {
                }
            } else {
                //请求安装未知应用来源的权限
                checkUpdate(context, urlName);
            }
        } else {
//            File file = new File(Environment.getExternalStorageDirectory() + "/" + BuildConfig.MX_USER_TYPE + "/apk/" + urlName);
            File downloads = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
            File file = new File(downloads  + "/" + BuildConfig.MX_USER_TYPE+ "/apk/" + urlName);
            if (file.exists()) {
                openFile(file, context);
            }
        }
    }
}
